const fs = require('fs');
const path = require('path');
const { compatibilityTree } = require('../src/compatibility-tree');

class CompatibilityCleaner {
  constructor() {
    this.baseDir = process.cwd();
  }

  async clean() {
    console.log('Cleaning compatibility layer...');
    
    // 清理旧的兼容层
    await this.cleanCompatibilityLayer();
    
    // 验证核心版本
    await this.validateCoreVersions();
    
    console.log('Compatibility cleanup completed!');
  }

  async cleanCompatibilityLayer() {
    const layerPath = path.join(this.baseDir, 'compatibility-layer');
    
    if (fs.existsSync(layerPath)) {
      // 保留env.json和.proto
      const keepFiles = ['env.json', 'proto'];
      
      fs.readdirSync(layerPath).forEach(item => {
        if (!keepFiles.includes(item)) {
          const itemPath = path.join(layerPath, item);
          this.removeRecursive(itemPath);
          console.log(`Removed: ${itemPath}`);
        }
      });
    }
  }

  async validateCoreVersions() {
    const modules = ['core', 'adapters', 'platform', 'wasm'];
    
    modules.forEach(module => {
      const modulePath = path.join(this.baseDir, 'src', module);
      if (fs.existsSync(modulePath)) {
        const versions = fs.readdirSync(modulePath)
          .filter(item => fs.lstatSync(path.join(modulePath, item)).isDirectory());
        
        if (versions.length === 0) {
          console.warn(`Warning: No versions found for ${module}`);
        }
      }
    });
  }

  removeRecursive(target) {
    if (fs.existsSync(target)) {
      if (fs.lstatSync(target).isDirectory()) {
        fs.readdirSync(target).forEach(item => {
          this.removeRecursive(path.join(target, item));
        });
        fs.rmdirSync(target);
      } else {
        fs.unlinkSync(target);
      }
    }
  }
}

// 执行清理
new CompatibilityCleaner().clean().catch(console.error);